<template>
  <div id="app">
    <keep-alive>
      <router-view/>
    </keep-alive>
  </div>
</template>

<script>

import basic_config from "./utils/global";
import bus from "@/utils/bus";

export default {
  name: 'App',
  data() {
    return {
      rec: null,
    }
  },
  methods: {
    initWebSocket: function () {
      try {
        var that = this;
        var webSocket = new WebSocket(basic_config.ws_url);//建立与服务端的连接
        webSocket.onopen = function () {
          sessionStorage.setItem("isConnected", 'true');
          console.log("WebSocket connect");
          webSocket.send("{hello:'*********************'}")
        };
        webSocket.onclose = function () {
          sessionStorage.setItem("isConnected", 'false');
          console.log("WebSocket disconnected");
          that.reconnect();
        };
        webSocket.onerror = function () {
          console.log("WebSocket server is error");
          sessionStorage.setItem("isConnected", 'false');
          that.reconnect();
        };
        webSocket.onmessage = function (event) {
          console.log("from server...");
          const res = JSON.parse(event.data);
          if (res.command === 'NETWORKING_UPDATE') {
            bus.$emit('serverData_network', res);
          } else if (res.command === 'MESSAGE_REPORT') {
            bus.$emit('serverData_msg', res);
          } else if (res.command === 'test_board_info') {
            bus.$emit('serverData_plat', res);
          }
        };
        this.$ws.setSocket(webSocket);
      } catch (e) {
        console.log("尝试建立连接失败" + e);
        this.reconnect();
      }
    }, reconnect: function () {
      if (this.$ws.socket && this.$ws.socket.readyState === WebSocket.OPEN) {
        return;
      }
      console.log('reconnect');
      this.rec && clearTimeout(this.rec);
      var that = this;
      this.rec = setTimeout(function () {
        that.initWebSocket();
      }, 5000);
    }
  },

  mounted() {
    if (this.$ws.socket && this.$ws.socket.readyState === WebSocket.OPEN) {
      return;
    }
    this.initWebSocket();

  }, destroyed() {
    console.log('destroyed!close ws');
    this.$ws.socket.close();
  },
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

html, body, #app {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}

.el-main {
  padding: 0;
}
</style>
